﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace SystemUpdatesCore.Files
{

    public class FileSave : IFileSave
    {
        /// <summary>
        /// 目录
        /// </summary>
        public string FilePath
        {
            get
            {
                var docPath= AppDomain.CurrentDomain.BaseDirectory;
                //var docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                var path = Path.Combine(docPath, "Updates");

                // 创建目录
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                return path;
            }
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task<T> Read<T>(string filePath)
        {
            var str = await File.ReadAllTextAsync(filePath);

            var list = str.ToObject<T>();

            return list;
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="values"></param>
        /// <param name="filePath"></param>
        public async Task Write<T>(T values, string filePath)
        {
            var str = values.ToString<T>();

            if (File.Exists(filePath))
                File.Delete(filePath);

            await File.WriteAllTextAsync($"{filePath}", str);
        }
    }
}

